class Event < ActiveRecord::Base
  belongs_to :series
  has_many :categorizations
  has_many :categories, :through => :categorizations
  validates_presence_of :name
  validates_presence_of :place
  validates_presence_of :start_time
  validate :event_ends_after_it_starts
  validate :event_is_not_in_the_past
  validate :event_starts_after_series_starts
  validate :event_ends_before_series_ends
  
  after_save :associations_categories_ids
  
  def event_ends_after_it_starts
    return if self.end_time.nil?
    self.errors.add(:end_time, 'must be after start date') if self.end_time <= self.start_time
  end
  
  def event_is_not_in_the_past
    self.errors.add(:start_time, 'can not be in the past') if self.start_time < Time.now
  end  
  
  def event_starts_after_series_starts
    return if self.is_a?(Series) || self.series.nil?
    self.errors.add(:start_time, 'event can not start before the series to which it belongs starts') if self.start_time < self.series.start_time
  end
  
  def event_ends_before_series_ends
    return if self.is_a?(Series) || self.series.nil? || self.series.end_time.nil? || self.end_time.nil?
    self.errors.add(:end_time, 'event can not end after the series to which it belongs ends') if self.end_time > self.series.end_time
  end
  
  # Look in Active::Record lifecycle
  def category_ids=(an_array_of_category_ids = [])
    # create new catrogizations from the category ids                       
    @category_ids = an_array_of_category_ids
  end             
  
  def associations_categories_ids
    return if @category_ids.nil?
    self.categorizations.clear
    @category_ids.each do |array|
      Categorization.new(:event_id => self.id, :category_id => array).save!
  end
  end
  
  def  set_some_shit(something)
    something
  end
end